package org.apache.ocean.solr.search;

import java.io.IOException;
import java.util.Set;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.ComplexExplanation;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.Similarity;
import org.apache.lucene.search.Weight;


public class ConstantScoreQuery extends Query {
	protected final DocSetCacheKey cacheKey;
	private Snapshot snapshot;
	private Timeout timeout;

	public ConstantScoreQuery(DocSetCacheKey cacheKey, Snapshot snapshot, Timeout timeout) {
		this.cacheKey = cacheKey;
		this.snapshot = snapshot;
		this.timeout = timeout;
	}

	public DocSetCacheKey getDocSetCacheKey() {
		return cacheKey;
	}

	public Query rewrite(IndexReader reader) throws IOException {
		return this;
	}

	public void extractTerms(Set terms) {
		// OK to not add any terms when used for MultiSearcher,
		// but may not be OK for highlighting
		// TODO: make work for highlighting
	}

	protected class ConstantWeight implements Weight {
		private Similarity similarity;
		private float queryNorm;
		private float queryWeight;

		public ConstantWeight(Searcher searcher) {
			this.similarity = getSimilarity(searcher);
		}

		public Query getQuery() {
			return ConstantScoreQuery.this;
		}

		public float getValue() {
			return queryWeight;
		}

		public float sumOfSquaredWeights() throws IOException {
			queryWeight = getBoost();
			return queryWeight * queryWeight;
		}

		public void normalize(float norm) {
			this.queryNorm = norm;
			queryWeight *= this.queryNorm;
		}

		public Scorer scorer(IndexReader reader) throws IOException {
			return new ConstantScorer(similarity, reader, this);
		}

		public Explanation explain(IndexReader reader, int doc) throws IOException {
			ConstantScorer cs = (ConstantScorer) scorer(reader);
			boolean exists = cs.bitSet.get(doc);

			ComplexExplanation result = new ComplexExplanation();

			if (exists) {
				result.setDescription("ConstantScoreQuery(" + cacheKey + "), product of:");
				result.setValue(queryWeight);
				result.setMatch(Boolean.TRUE);
				result.addDetail(new Explanation(getBoost(), "boost"));
				result.addDetail(new Explanation(queryNorm, "queryNorm"));
			} else {
				result.setDescription("ConstantScoreQuery(" + cacheKey + ") doesn't match id " + doc);
				result.setValue(0);
				result.setMatch(Boolean.FALSE);
			}
			return result;
		}
	}

	protected class ConstantScorer extends Scorer {
		final float theScore;
		int doc = -1;
		BitDocSet bitDocSet;
		OpenBitSet bitSet;

		public ConstantScorer(Similarity similarity, IndexReader reader, Weight w) throws IOException {
			super(similarity);
			theScore = w.getValue();
			try {
				IndexSnapshot indexSnapshot = snapshot.getIndexSnapshot(reader);
				bitDocSet = indexSnapshot.getDocSet(cacheKey, timeout);
				bitSet = bitDocSet.getBits();
			} catch (Exception exception) {
				Util.throwAsIOException(exception);
			}
		}

		public boolean next() throws IOException {
			doc = bitSet.nextSetBit(doc + 1);
			return doc >= 0;
		}

		public int doc() {
			return doc;
		}

		public float score() throws IOException {
			return theScore;
		}

		public boolean skipTo(int target) throws IOException {
			doc = bitSet.nextSetBit(target);
			return doc >= 0;
		}

		public Explanation explain(int doc) throws IOException {
			throw new UnsupportedOperationException();
		}
	}

	protected Weight createWeight(Searcher searcher) {
		return new ConstantScoreQuery.ConstantWeight(searcher);
	}

	/** Prints a user-readable version of this query. */
	public String toString(String field) {
		return "ConstantScore(" + cacheKey.toString() + (getBoost() == 1.0 ? ")" : "^" + getBoost());
	}

	/** Returns true if <code>o</code> is equal to this. */
	public boolean equals(Object o) {
		if (this == o)
			return true;
		if (!(o instanceof ConstantScoreQuery))
			return false;
		ConstantScoreQuery other = (ConstantScoreQuery) o;
		return this.getBoost() == other.getBoost() && cacheKey.equals(other.cacheKey);
	}
}
